//
//  WaterfallFlowLayout.m
//  MJTableViewDemo
//
//  Created by ihope on 2018/5/14.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "WaterfallFlowLayout.h"

@interface WaterfallFlowLayout()

/** 存放每列高度字典*/
@property (nonatomic, strong) NSMutableDictionary *dicOfheight;
/** 存放所有item的attrubutes属性*/
@property (nonatomic, strong) NSMutableArray *array;
/** 计算每个item高度的block，必须实现*/
@property (nonatomic, copy) HeightBlock block;

@end

@implementation WaterfallFlowLayout


-(instancetype)init{
    self =  [super init];
    if (self) {
        
        ///默认行数
        self.lineNumber = 2;
        ///行间距
        self.rowSpacing = 5.;
        ///列间距
        self.lineSpacing = 5.;
        ///内边距
        self.sectionInset = UIEdgeInsetsMake(5., 5., 5., 5.);
        
        self.dicOfheight = [NSMutableDictionary dictionary];
        self.array = [NSMutableArray array];
        
    }
    return self;
}
-(void)prepareLayout{
    [super prepareLayout];
    
    NSInteger count = [self.collectionView numberOfItemsInSection:2];
    for (NSInteger i = 0; i < self.lineNumber; i ++ ) {
        [self.dicOfheight setObject:@(self.sectionInset.top) forKey:[@(i) stringValue]];
    }
    for (NSInteger i = 0; i < count; i ++ ) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:2];
        [self.array addObject:[self layoutAttributesForItemAtIndexPath:indexPath]];
    }
    
}
/**
 *设置可滚动区域范围
 */
-(CGSize)collectionViewContentSize{
    NSLog(@"collectionViewContentSize");
    __block NSString *maxHeightLine = 0;
    [self.dicOfheight enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if ([self.dicOfheight[maxHeightLine] floatValue] < [obj floatValue]) {
            maxHeightLine = key;
        }
    }];
    return CGSizeMake(self.collectionView.bounds.size.width, [self.dicOfheight[maxHeightLine] floatValue] + self.sectionInset.bottom);
}
/**
 *返回视图框内的item 属性 可以直接返回所有的item
 */
-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    return self.array;
}

-(void)computeIndexCellHeightWithWidthBlock:(HeightBlock)block{
    if (self.block != block) {
        self.block = block;
    }
}

-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
    
}

@end
